package cumeo89.chii.client.entry.editor;

import static com.google.gwt.event.dom.client.KeyCodes.*;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;

import cumeo89.chii.client.entry.AbstractEditor;
import cumeo89.chii.client.ui.AutoResizeTextBox;

public class WikitextEditor extends AbstractEditor implements KeyUpHandler {

	private AutoResizeTextBox textBox = new AutoResizeTextBox();

	public WikitextEditor() {
		textBox.setStyleName("editor");
		textBox.addKeyUpHandler(this);
	}

	@Override
	protected Widget getEditorWidget() {
		return textBox;
	}

	@Override
	public void startEditing(String value, int left, int top, int width,
			int height) {
		textBox.setResizeSupressed(true);
		textBox.setMinWidth(width);
		textBox.setMaxWidth(Window.getClientWidth() - left - 2);
		textBox.setText(value);
		textBox.setResizeSupressed(false);

		TextEditorController.getInstance().registerText(textBox);
		super.startEditing(value, left, top, width, height);
		textBox.selectAll();
		textBox.setFocus(true);
	}

	@Override
	public boolean stopEditing() {
		TextEditorController.getInstance().unregisterText(textBox);
		value = textBox.getText();
		return super.stopEditing();
	}

	@Override
	public void cancelEditing() {
		TextEditorController.getInstance().unregisterText(textBox);
		super.cancelEditing();
	}

	public void onKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KEY_ESCAPE) {
			cancelEditing();
		} else if (event.getNativeKeyCode() == KEY_ENTER) {
			stopEditing();
		}
	}

}
